'use strict';

let { Sequelize, DataTypes } = require('sequelize');
let { database, username, password, host, dialect } = require('./config');

//创建实例
let sequelize = new Sequelize(database, username, password, {
    host: host,
    dialect: dialect
});

//定义模型模板
function modelList(name, attrs) {
    let prop = {};
    //将外部定义的模型的属性全部加载进来
    for (let key in attrs) {
        let value = attrs[key];
        prop[key] = value;
    }

    prop.id = {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
    };
    prop.createAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };
    prop.updateAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };
    prop.version = {
        type: DataTypes.BIGINT,
        allowNull: false
    }
    prop.remarks = {
        type: DataTypes.STRING,
        allowNull: true
    }

    //利用sequelize的实例定义一个模型的方式
    let obj = sequelize.define(name, prop, {
        //表名称等于模型名称
        tableName: name,
        //不自动创建createAt,updateAt两字段
        timestamps: false,
        //钩子🐕
        hooks: {
            //在插入或更新数据到数据库时进行的验证判断
            beforeValidate: function (obj) {
                let now = Date.now();
                if (obj.isNewRecord) {
                    obj.createAt = now;
                    obj.updateAt = now;
                    obj.version = 0;
                } else {
                    obj.updateAt = now;
                    obj.version += 1;
                }
            }
        }
    });
    return obj;
}

module.exports = {
    sequelize,
    modelList,
    DataTypes
}
